package com.sakhalin.news.ui.news


import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.google.accompanist.pager.*
import com.sakhalin.news.network.DataLoadingState
import com.sakhalin.news.ui.other.ErrorView
import com.sakhalin.news.ui.other.LoadingView
import com.sakhalin.news.ui.theme.BlueDark
import com.sakhalin.news.viewmodels.NewsCategoriesViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalPagerApi::class)
@Composable
fun NewsPage(
    navController: NavHostController,
    viewModel: NewsCategoriesViewModel = viewModel(modelClass = NewsCategoriesViewModel::class.java),
) {
    val loadingState by viewModel.loadingState.collectAsState()
    val newsCategories by viewModel.newsCategoriesState.collectAsState()
    val pagerState = rememberPagerState()
    val coroutineScope = rememberCoroutineScope()
    val isLightTheme = MaterialTheme.colors.isLight

    Column(
        modifier = Modifier.background(if (isLightTheme) Color.White else Color.Black)
    ) {
        when (loadingState) {
            //Пока контент не получен, то отображаем прогресс загрузки
            is DataLoadingState.Loading -> {
                LoadingView()
            }
            //Контент получен! Рисуем UI
            is DataLoadingState.LoadingSuccess -> {
                //Создаем Табы с рубриками
                ScrollableTabRow(
                    edgePadding = 0.dp,
                    backgroundColor = if (isLightTheme) Color.White else Color.Black,
                    contentColor = if (isLightTheme) BlueDark else Color.White,
                    selectedTabIndex = pagerState.currentPage,
                    indicator = { tabPositions ->
                        TabRowDefaults.Indicator(
                            modifier = Modifier.pagerTabIndicatorOffset(pagerState, tabPositions)
                        )
                    }
                ) {
                    newsCategories.forEachIndexed { index, newsCategoryItem ->
                        Tab(
                            text = { Text(newsCategoryItem.name) },
                            selected = pagerState.currentPage == index,
                            modifier = Modifier.fillMaxWidth(),
                            onClick = { coroutineScope.launch { pagerState.animateScrollToPage(index) } },
                        )
                    }
                }

                //Создаем ViewPage-ры c списком новостей
                HorizontalPager(
                    state = pagerState,
                    count = newsCategories.size,
                    modifier = Modifier.fillMaxSize(),
                    verticalAlignment = Alignment.Top
                ) { page -> 
                    Surface {
                        NewsListView(category = newsCategories[page].category, navController = navController)
                    }
                }
            }
            //Произошла ошибка. Отображаем ошибку
            is DataLoadingState.ErrorLoading -> {
                ErrorView(errorText = (loadingState as DataLoadingState.ErrorLoading).error, onClickRetry = {
                    viewModel.getCategories()
                })
            }
        }
    }


}

